/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },

    // deviceready Event Handler
    //
    // Bind any cordova events here. Common events are:
    // 'pause', 'resume', etc.
    onDeviceReady: function() {
        this.receivedEvent('deviceready');
    },

    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};

app.initialize();

window.onload = function() {
    document.getElementById("toast").addEventListener("click", function() {
        EbeiPlugins.showToast("toastTest");
        //cordova.exec(function() {}, function(){}, "EbeiPlugins", "showToast", ["123"]);
    });

    document.getElementById("doSQL").addEventListener("click", function() {
//        var db = window.sqlitePlugin.openDatabase({name:'daichangkui_ebei.db', location: 'default'});
//        db.transaction(function(tx){
//            tx.executeSql("CREATE TABLE IF NOT EXISTS CrashInfoTable(id integer primary key, appVersion text, androidVersion text, deviceInfo text)", [],
//            function(tx, rs) {
//                console.log('success');
//            }, function(tx, error) {
//                alert(error.message);
//                console.log('error:' + error.message);
//            });
//        });
//        db.transaction(function(tx){
//            tx.executeSql("INSERT INTO CrashInfoTable(appVersion, androidVersion, deviceInfo) VALUES (?,?,?)", ["test7.0", "androidtest1.1", "测试哈哈"],
//            function(tx, rs) {
//                console.log('success');
//            }, function(tx, error) {
//                alert(error.message);
//                console.log('error:' + error.message);
//            });
//        });

        insertProblemRecord("111");
    });

    document.getElementById("displaySQL").addEventListener("click", function() {
        initProblemRecord();
        var db = openDatabase();
        db.transaction(function(tx){
            tx.executeSql(selectProblemRecordDB(""), [],
            function(tx, rs) {
                alert(rs.rows.length);
                console.log('success');
            }, function(tx, error) {
                alert(error.message);
                console.log('error:' + error.message);
            });
        });
    });
}

function initProblemRecord() {
  cordova.exec(function() {
      alert("Toast success");
  }, function(msg){
      alert("Toast faile" + msg)
  }, "EbeiPlugins", "showToast", ["123"]);
  var db = openDatabase();
  db.transaction(function(tx){
    tx.executeSql(createProblemRecordDB(), [],
      function(tx, rs) {
        console.log('success');
      }, function(tx, error) {
        alert(error.message);
        console.log('error:' + error.message);
      });
  });
}

    function insertProblemRecord(detailId) {
      initProblemRecord();
      var db = openDatabase();
      db.transaction(function(tx){
        tx.executeSql(selectProblemRecordDB(""), [],
        function(tx, rs) {
          console.log('success');
          alert(rs.rows.length);

            if (rs.rows.length > 0) {
                tx.executeSql(updateProblemRecordDB(), ["androidtest1.1", "测试哈哈","test7.0", "androidtest1.1", "测试哈哈",
                  "test7.0", "androidtest1.1", "测试哈哈","test7.0", "androidtest1.1", "测试哈哈","test7.0", "androidtest1.1", "测试哈哈", "测试哈哈", detailId],
                function(tx, rs) {
                  console.log('success');
                }, function(tx, error) {
                  alert(error.message);
                  console.log('error:' + error.message);
                });
            } else {
                tx.executeSql(insertProblemRecordDB(), [detailId, "androidtest1.1", "测试哈哈","test7.0", "androidtest1.1", "测试哈哈",
                  "test7.0", "androidtest1.1", "测试哈哈","test7.0", "androidtest1.1", "测试哈哈","test7.0", "androidtest1.1", "测试哈哈", "测试哈哈"],
                function(tx, rs) {
                  console.log('success');
                  alert("insert");
                }, function(tx, error) {
                  alert(error.message);
                  console.log('error:' + error.message);
                });
             }
        }, function(tx, error) {
          alert(error.message);
          console.log('error:' + error.message);
        });
    });
  }

  function openDatabase() {
    var databaseName = localStorage.username + '_ebei.db';
    var db = window.sqlitePlugin.openDatabase({name:databaseName, location: 'default'});
    return db;
  }

  function getProblemDetailTableName() {
        return "InspectionProblemRecordTable";
      }

      function createProblemRecordDB() {
        var sql = "CREATE TABLE IF NOT EXISTS " + getProblemDetailTableName() + " (" +
          "id integer primary key autoincrement not null" +
          ", detailId text" +
          ", problemCategory text" +
          ", problemId text" +
          ", detailRecord text" +
          ", detailSubmitUserId text" +
          ", detailSubmitTime text" +
          ", detailStatus text" +
          ", detailSync text" +
          ", detailSubmitUserName text" +
          ", attachmentFlag text" +
          ", pauseStatus text" +
          ", closeStatus text" +
          ", reasonId text" +
          ", pauseDeadline text" +
          ", recordType text" +
          ", moduleType text" +
          ")";
          return sql;
      }

      function insertProblemRecordDB() {
        var sql = "insert into " + getProblemDetailTableName() + " (detailId, problemCategory, problemId, detailRecord, detailSubmitUserId" +
           ", detailSubmitTime, detailStatus, detailSync, detailSubmitUserName, attachmentFlag, pauseStatus, closeStatus, reasonId" +
           ", pauseDeadline, recordType, moduleType) " +
           "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        alert(sql);
        return sql;
      }

      function updateProblemRecordDB() {
        var sql = "update " + getProblemDetailTableName() + " set " +
            "problemCategory = ?" +
            ", problemId = ?" +
            ", detailRecord = ?" +
            ", detailSubmitUserId = ?" +
            ", detailSubmitTime = ?" +
            ", detailStatus = ?" +
            ", detailSync = ?" +
            ", detailSubmitUserName = ?" +
            ", attachmentFlag = ?" +
            ", pauseStatus = ?" +
            ", closeStatus = ?" +
            ", reasonId = ?" +
            ", pauseDeadline = ?" +
            ", recordType = ?" +
            ", moduleType = ?" +
            " where detailId = ?";
        alert(sql);
        return sql;
      }

      function selectProblemRecordDB(detailId) {
        var sql = "select * from " + getProblemDetailTableName();
        if (detailId != null && detailId.length > 0) {
          sql += " where detailId = '" + detailId + "'";
        }
        alert(sql);
        return sql;
      }
